package Z11_4_synchronizedControl;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author： pang-yun
 * @date： 2021-11-05 14:27
 * 功能目的 ：用于
 */

public class AlternateAwaitSignal {
    public static void main(String[] args) throws InterruptedException {
        AwaitSignal awaitSignal = new AwaitSignal(5);
        Condition a = awaitSignal.newCondition();
        Condition b = awaitSignal.newCondition();
        Condition c = awaitSignal.newCondition();

        new Thread(() -> {
            awaitSignal.print(a, b, "a");
        }).start();

        new Thread(() -> {
            awaitSignal.print(b, c, "b");
        }).start();

        new Thread(() -> {
            awaitSignal.print(c, a, "c");
        }).start();

        TimeUnit.SECONDS.sleep(1);

        awaitSignal.lock();
        try {
            a.signal();
        }finally {
            awaitSignal.unlock();
        }

    }
}

@Data
@AllArgsConstructor
class AwaitSignal extends ReentrantLock {
    private int loopNumber;

    public void print(Condition current, Condition next, String str) {
        for (int i = 0; i < loopNumber; i++) {
            lock();
            try {
                current.await();
                System.out.print(str);
                next.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                unlock();
            }
        }
    }
}

